<?php

namespace ShineYork\LaravelExtend\Swoole\Http;

use Illuminate\Http\Response as LaravelResponse;
use Swoole\Http\Response as SwooleResponse;

class SResponse
{

    protected $laravelResponse;
    protected $swooleResponse;

    public function __construct($laravelResponse, $swooleResponse)
    {
        $this->laravelResponse = $laravelResponse;
        $this->swooleResponse = $swooleResponse;
    }
    //解析swoole请求
    public static function make(LaravelResponse $laravelResponse, SwooleResponse $swooleResponse)
    {
         return new static($laravelResponse, $swooleResponse);
    }

    //输出响应结果
    public function send()
    {
         $this->sendHeader();
         $this->sendContent();
    }

    //输出头部
    public function sendHeader()
    {
        //参考Symfony\Component\HttpFoundation\Response
        $larvelResponse = $this->laravelResponse;

        $headers = $larvelResponse->headers->allPreserveCase();

        //1. 因为swoole有自己的设置token的方式，所以这里需要删除
        if( isset($headers['Set-Cookie']) ) {
            unset($headers['Set-Cookie']);
        }

        foreach ($headers as $name => $values) {
            foreach ($values as $value) {
                $this->swooleResponse->header($name, $value);
            }
        }

        //2. 设置状态
        $this->swooleResponse->status($larvelResponse->getStatusCode());

        //3. 设置cookie
        //Symfony\Component\HttpFoundation\ResponseHeaderBag
        foreach ($larvelResponse->headers->getCookies() as $cookie) {
            $this->swooleResponse->cookie(
                $cookie->getName(),
                $cookie->getValue(),
                $cookie->getExpiresTime(),
                $cookie->getPath(),
                $cookie->getDomain(),
                $cookie->isSecure(),
                $cookie->isHttpOnly()
            );
        }

    }

    //输出主要内容
    public function sendContent()
    {
        $this->swooleResponse->end($this->laravelResponse->getContent());
    }


}
